package com.yangsir.mysite.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yangsir.mysite.Dto.VisitDto;
import com.yangsir.mysite.Dto.WeekDto;
import com.yangsir.mysite.common.R;
import com.yangsir.mysite.pojo.Visitcount;
import com.yangsir.mysite.service.VisitcountService;
import com.yangsir.mysite.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;

/**
 * java 8
 */
@EnableScheduling
@RestController
@RequestMapping("/visit")
@CrossOrigin
public class VisitCountController {

    @Autowired
    private VisitcountService visitcontService;
    @Autowired
    private RedisUtils redisUtils;

    private final String VISIT_COUNT_KEY = "visit_count";
    private final String VISIT_ALL_COUNT_KEY = "visit_all_count";

    /**
     * 获取访问数据
     * @param httpServletRequest
     * @return
     */
    @GetMapping("/webData")
    public R<VisitDto> visitData(HttpServletRequest httpServletRequest){
        return visitcontService.visitData(httpServletRequest);
    }

    @GetMapping("/weekData")
    public R<WeekDto> weekData(){
        return visitcontService.weekData();
    }

    /**
     * 定时任务
     * 每天凌晨0点存储一条数据
     */
    @Scheduled(cron = "0 0 0 * * *")
    public void saveVisitCount() {
        visitcontService.save(new Visitcount());
        if (redisUtils.exists(VISIT_COUNT_KEY)) {
//            删除上一天的每日访问量数据
            redisUtils.removeSet(VISIT_COUNT_KEY);
            redisUtils.removeSet(VISIT_ALL_COUNT_KEY);

        }
        System.out.println("存储一条数据");
    }

    /**
     * 定时任务
     * 每过30分钟将Redis数据更新到数据库
     */
    @Scheduled(cron = "0 2 * * * *")
    public void updateVisitCount() {
        LambdaQueryWrapper<Visitcount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Visitcount::getCreateTime, LocalDate.now());
        Visitcount one = visitcontService.getOne(queryWrapper);
        System.out.println(redisUtils.exists(VISIT_COUNT_KEY));
        if (one != null && redisUtils.exists(VISIT_COUNT_KEY)) {
            one.setVCount(Integer.parseInt(redisUtils.get(VISIT_COUNT_KEY)+""));
            visitcontService.update(one, queryWrapper);
            System.out.println("更新一条数据");
        } else {
            System.out.println("更新失败");
        }

    }
}
